﻿
package com.sgcc.nfc.lock.data.repository

import com.sgcc.nfc.lock.core.network.NetworkResult
import com.sgcc.nfc.lock.core.network.safeApiCall
import com.sgcc.nfc.lock.core.util.DateUtils
import com.sgcc.nfc.lock.data.remote.api.LockApi
import com.sgcc.nfc.lock.data.remote.api.LogApi
import com.sgcc.nfc.lock.data.remote.api.RoomApi
import com.sgcc.nfc.lock.data.remote.api.WarningApi
import com.sgcc.nfc.lock.domain.model.DashboardStats
import com.sgcc.nfc.lock.domain.repository.DashboardRepository
import javax.inject.Inject

class DashboardRepositoryImpl @Inject constructor(
    private val lockApi: LockApi,
    private val warningApi: WarningApi,
    private val roomApi: RoomApi,
    private val logApi: LogApi
) : DashboardRepository {

    override suspend fun getDashboardStats(): NetworkResult<DashboardStats> {
        val totalLocks = safeApiCall {
            lockApi.getLocks(pageNum = 1, pageSize = 1)
        }
        val openLocks = safeApiCall {
            lockApi.getLocks(pageNum = 1, pageSize = 1, status = 1)
        }
        val closedLocks = safeApiCall {
            lockApi.getLocks(pageNum = 1, pageSize = 1, status = 0)
        }
        val pendingWarnings = safeApiCall {
            warningApi.getWarnings(pageNum = 1, pageSize = 1, status = 0)
        }
        val rooms = safeApiCall {
            roomApi.getRooms(pageNum = 1, pageSize = 1)
        }
        val logs = safeApiCall {
            logApi.getLogs(
                pageNum = 1,
                pageSize = 1,
                startTime = DateUtils.todayStart(),
                endTime = DateUtils.todayEnd()
            )
        }

        if (listOf(totalLocks, openLocks, closedLocks, pendingWarnings, rooms, logs).any { it is NetworkResult.Error }) {
            val error = (listOf(totalLocks, openLocks, closedLocks, pendingWarnings, rooms, logs)
                .filterIsInstance<NetworkResult.Error>()
                .firstOrNull())
            return error ?: NetworkResult.Error(-1, "统计信息加载失败")
        }

        val totalLocksCount = (totalLocks as? NetworkResult.Success)?.data?.total?.toInt() ?: 0
        val openLocksCount = (openLocks as? NetworkResult.Success)?.data?.total?.toInt() ?: 0
        val closedLocksCountFromApi = (closedLocks as? NetworkResult.Success)?.data?.total?.toInt()
        val closedLocksCount = closedLocksCountFromApi ?: (totalLocksCount - openLocksCount).coerceAtLeast(0)

        val stats = DashboardStats(
            totalLocks = totalLocksCount,
            openLocks = openLocksCount,
            closedLocks = closedLocksCount,
            pendingWarnings = (pendingWarnings as? NetworkResult.Success)?.data?.total?.toInt() ?: 0,
            totalRooms = (rooms as? NetworkResult.Success)?.data?.total?.toInt() ?: 0,
            todayOperations = (logs as? NetworkResult.Success)?.data?.total?.toInt() ?: 0
        )
        return NetworkResult.Success(stats)
    }
}
